<?php  

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class product extends CI_Controller {
	function __construct()
	{
		parent::__construct();
		
		// check if user logged in 
		if (!$this->ion_auth->logged_in())
	  	{
			redirect('auth/login');
	  	}		
		$this->load->library('form_validation');
		$this->load->model('product/product_model');
		$this->load->library('datatables');			
	}
	
	function get(){
		echo $this->product_model->get();
	}
		
	
	function create_product()
	{
		
		$this->data['page_title'] = "Create product";
		$meta['page_title'] = "Create product";
		$this->data['categories']=$this->product_model->get_category();
		$this->data['companies']=$this->product_model->get_company();
		$this->data['units']=$this->product_model->get_unit();
		$this->data['branches']=$this->product_model->get_branchlist();
		//print_r($this->data['units']);exit;
		if($this->data['branches']==''){
			$this->data['branches']=array();
		}
		if($this->data['units']==''){
			$this->data['units']=array();
		}
	
		if($this->data['categories']==''){
			$this->data['categories']=array();
		}
		if($this->data['companies']==''){
			$this->data['companies']=array();
		}
		
		
		
		/*if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
		{
			redirect('auth', 'refresh');
		}for checking the authentication*/

		//validate form input
		$this->form_validation->set_rules('name', 'product Name', 'required|xss_clean');
		$this->form_validation->set_rules('code', 'product Code', 'required|is_unique[product.code]');
		$this->form_validation->set_rules('id_category', 'Category', 'required|is_natural|xss_clean|callback_check_category_name');
		$this->form_validation->set_rules('id_company', 'Company', 'required|is_natural|xss_clean|callback_check_company_name');
		$this->form_validation->set_rules('id_unit', 'Unit', 'required|is_natural|xss_clean|callback_check_unit_name');
		$this->form_validation->set_rules('purchase_price', 'Purchase Price', 'required|xss_clean');
		$this->form_validation->set_rules('selling_price', 'Selling Price', 'required|xss_clean');
		$this->form_validation->set_rules('opening_stock', 'Opening Stock', 'required|xss_clean');
		$this->form_validation->set_rules('alert_quantity', 'Alert Quantity', 'required|xss_clean');
		if ($this->form_validation->run() == true)
		{
			if($this->input->post('cat_name')!=''){
				$cat_data = array(
				'name'=> strtoupper($this->input->post('cat_name')),
				'description'=>strtoupper( $this->input->post('cat_desc')),
				);
				$cat_id = $this->product_model->insert_category($cat_data); 
			}else{
				$cat_id = $this->input->post('id_category');
				
			}
			
			if($this->input->post('comp_name')!=''){
				$comp_data = array(
				'name'=> strtoupper($this->input->post('comp_name')),
				'description'=> strtoupper($this->input->post('comp_desc')),
				); 
				$comp_id = $this->product_model->insert_company($comp_data); 
			}else{
				
				$comp_id = $this->input->post('id_company');
			}
			
			if($this->input->post('unit_name')!=''){
				$unit_data = array(
				'name'=> strtoupper($this->input->post('unit_name')),
				'description'=> strtoupper($this->input->post('unit_desc')),
				); 
				$unit_id = $this->product_model->insert_unit($unit_data); 
			
			}else{
				
				$unit_id = $this->input->post('id_unit');	
			}
		
		
			if($this->input->post('id_branch')=='0'){
				$id_branch = '0';	
			
			}else{
				
				$id_branch = $this->input->post('id_branch');
			}	
			
			$additional_data = array(
				'name' => strtoupper($this->input->post('name')),
				'code' => strtoupper($this->input->post('code')),
				'id_category'  => $cat_id,
				'id_company'  => $comp_id,
				'id_unit'  => $unit_id,
				'purchase_price'  => $this->input->post('purchase_price'),
				'selling_price'  => $this->input->post('selling_price'),
				'id_branch'  => $id_branch,
				'opening_stock'  => $this->input->post('opening_stock'),
				'alert_quantity'  => $this->input->post('alert_quantity'),
				'ip'			=>	$_SERVER['REMOTE_ADDR']
			);
			
			//print_r($additional_data);exit;
			
		}
		if ($this->form_validation->run() == true) 
		{
			$this->product_model->insert($additional_data);
			redirect("product/product/get_all_product");
			//check to see if we are creating the user
			//redirect them back to the admin page
			//$this->session->set_flashdata('message', $this->ion_auth->messages());
			//redirect("auth", 'refresh');
		}
		else
		{
			//display the create user form
			//set the flash data error message if there is one
			$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

			$this->data['name'] = array(
				'name'  => 'name',
				'id'    => 'name',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('name'),
			);
			$this->data['code'] = array(
				'name'  => 'code',
				'id'    => 'code',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('code'),
			);
		
			
			$this->data['id_category'] = array(
				'name'  => 'id_category',
				'id'    => 'id_category',
				'type'  => 'select',
				'value' => $this->form_validation->set_value('id_category'),
			);
				$this->data['id_company'] = array(
				'name'  => 'id_company',
				'id'    => 'id_company',
				'type'  => 'select',
				'value' => $this->form_validation->set_value('id_company'),
			);
			$this->data['id_unit'] = array(
				'name'  => 'id_unit',
				'id'    => 'id_unit',
				'type'  => 'select',
				'value' => $this->form_validation->set_value('id_unit'),
			);
			
			$this->data['id_branch'] = array(
				'name'  => 'id_branch',
				'id'    => 'id_branch',
				'type'  => 'select',
				'value' => $this->form_validation->set_value('id_branch'),
			);
			$this->data['purchase_price'] = array(
				'name'  => 'purchase_price',
				'id'    => 'purchase_price',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('purchase_price'),
			);

			$this->data['selling_price'] = array(
				'name'  => 'selling_price',
				'id'    => 'selling_price',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('selling_price'),
			);
			
			$this->data['opening_stock'] = array(
				'name'  => 'opening_stock',
				'id'    => 'opening_stock',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('opening_stock'),
			);

			$this->data['alert_quantity'] = array(
				'name'  => 'alert_quantity',
				'id'    => 'alert_quantity',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('alert_quantity'),
			);

			

		//	print_r($this->data);exit;

			$this->load->view('common/header',$meta);
			$this->load->view('product/product/create_product', $this->data);
			$this->load->view('common/footer');
		}
	}
	
	function get_all_product(){
		//list the users
		//echo "i am here";
		
		$this->data['users'] = $this->product_model->get_productList()->result();
			
			//print_r($this->data['users']);exit; 
	// $this->data['user_type'] =  $this->ion_auth_model->get_user_type($this->session->userdata('user_id'))->row();
	  //echo $get_user_type->name;
	   
	  // exit;
	   $meta['page_title'] = "products List";
	   $this->data['message'] = "product Added Successfully";
	 //  $this->session->set_flashdata('message', 'User Created Successfully');
	   $this->load->view('common/header', $meta);
	   $this->load->view('product/product/view_product1');
       $this->load->view('common/footer');
	   
		}
	

	function edit_product($id)
	{
		
	$this->data['page_title'] = "Edit product";
		$this->data['categories']=$this->product_model->get_category();
		$this->data['companies']=$this->product_model->get_company();
		$this->data['units']=$this->product_model->get_unit();
		$this->data['branches']=$this->product_model->get_branchlist();

//	$this->data['groups']=$this->product_model->get_product();
		if (!$this->ion_auth->logged_in())
		{
			redirect('auth', 'refresh');
		}

		$user = $this->product_model->get_product($id)->row();
		$product = $this->product_model->get_product($id)->row_array();
	//$branch_product['opening_stock'] = $branch_product['opening_stock'] - $product['opening_stock'] ;
		//$groups=$this->ion_auth->groups()->result_array();
		//$currentGroups = $this->ion_auth->get_users_groups($id)->result();
		
		//getting the user type ex. team lead 
		//$get_user_type = $this->ion_auth_model->user_type()->result_array();
		 //$currentUser = $this->ion_auth_model->get_user_type($id)->result();
		
		//getting the user type ex. fedonic 
		//$get_departments = $this->ion_auth_model->departments()->result_array();
		 //$currentDepartments = $this->ion_auth_model->get_user_department($id)->result();
		
		//process the phone number
		//if (isset($user->phone) && !empty($user->phone))
	//	{
			//$user->phone = explode('-', $user->phone);
		//}

		//validate form input
		
		
		$this->form_validation->set_rules('name', 'product Name', 'required|xss_clean');
		$this->form_validation->set_rules('code', 'product Code', 'required');
		$this->form_validation->set_rules('id_category', 'Category', 'required|is_natural_no_zero|xss_clean');
		$this->form_validation->set_rules('id_company', 'Company', 'required|is_natural_no_zero|xss_clean');
		$this->form_validation->set_rules('purchase_price', 'Purchase Price', 'required|xss_clean');
		$this->form_validation->set_rules('selling_price', 'Selling Price', 'required|xss_clean');
		$this->form_validation->set_rules('opening_stock', 'Opening Stock', 'required|xss_clean');
		$this->form_validation->set_rules('alert_quantity', 'Alert Quantity', 'required|xss_clean');
		
		
		
		
		
		
		/*$this->form_validation->set_rules('phone2', 'Second Part of Phone', 'required|xss_clean|min_length[3]|max_length[3]');
		$this->form_validation->set_rules('phone3', 'Third Part of Phone', 'required|xss_clean|min_length[4]|max_length[4]');
		$this->form_validation->set_rules('company', 'Company Name', 'required|xss_clean');*/
		
		//$this->form_validation->set_rules('groups', 'Groups', 'xss_clean');

		if (isset($_POST) && !empty($_POST))
		{
			// do we have a valid request?
			/*if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
			{
				show_error('This form post did not pass our security checks.');
			}*/
			//echo $this->input->post('id_branch');exit;
			 if($this->input->post('id_branch')!='0'){
				$branch_product = $this->product_model->edit_branchproduct($id)->row_array();
				if($product['opening_stock']!= intval($this->input->post('opening_stock'))){
					//echo "i am here";exit;
					$branch_product['opening_stock'] = $branch_product['opening_stock'] - $product['opening_stock'] +  intval($this->input->post('opening_stock'));
				}			
			 }else{
		$branch_product = $this->product_model->edit_warehouseproduct($id)->row_array();

				if($product['opening_stock']!= intval($this->input->post('opening_stock'))){
					$branch_product['opening_stock'] = $branch_product['opening_stock'] - $product['opening_stock'] +  intval($this->input->post('opening_stock'));
				}
				
			 }

			
			$data = array(
				'name' => strtoupper($this->input->post('name')),
				'code' =>strtoupper( $this->input->post('code')),
				'id_category'  => $this->input->post('id_category'),
				'id_company'  => $this->input->post('id_company'),
				'id_unit'  => $this->input->post('id_unit'),
				'purchase_price'  => $this->input->post('purchase_price'),
				'selling_price'  => $this->input->post('selling_price'),
				'id_branch'  => $this->input->post('id_branch'),
				/*'opening_stock'  => $this->input->post('opening_stock'),*/
				'alert_quantity'  => $this->input->post('alert_quantity'),
				'ip'			=>	$_SERVER['REMOTE_ADDR']
			);
		
			//print_r($data);exit;
			//print_r($user->id);exit;
			//Update the groups user belongs to
			if ($this->form_validation->run() === TRUE)
			{
				$this->product_model->update($user->id, $data,$branch_product);
				redirect("product/product/get_all_product");
				//check to see if we are creating the user
				//redirect them back to the admin page
			}
		}

		//display the edit user form
		//$this->data['csrf'] = $this->_get_csrf_nonce();

		//set the flash data error message if there is one
		$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

		//pass the user to the view
		$this->data['user'] = $user;
		//$this->data['groups'] = $groups;
		//$this->data['currentGroups'] = $currentGroups;
		
		//user type 
		
		//$this->data['user_type'] = $get_user_type;
	//	$this->data['currentUser'] = $currentUser;
		
		//user departments
		
		//$this->data['get_departments'] = $get_departments;
		//$this->data['currentDepartments'] = $currentDepartments;		
		

		$this->data['name'] = array(
				'name'  => 'name',
				'id'    => 'name',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('name', $user->name),
			);
			$this->data['code'] = array(
				'name'  => 'code',
				'id'    => 'code',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('code', $user->code),
			);
		
			
			$this->data['id_category'] = array(
				'name'  => 'id_category',
				'id'    => 'id_category',
				'type'  => 'select',
				'value' => $this->form_validation->set_value('id_category',$user->id_category),
			);
				$this->data['id_company'] = array(
				'name'  => 'id_company',
				'id'    => 'id_company',
				'type'  => 'select',
				'value' => $this->form_validation->set_value('id_company', $user->id_company),
			);
			$this->data['id_unit'] = array(
				'name'  => 'id_unit',
				'id'    => 'id_unit',
				'type'  => 'select',
				'value' => $this->form_validation->set_value('id_unit',$user->id_unit),
			);
			$this->data['id_branch'] = array(
				'name'  => 'id_branch',
				'id'    => 'id_branch',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('id_branch',$user->id_branch),
			);
			$this->data['purchase_price'] = array(
				'name'  => 'purchase_price',
				'id'    => 'purchase_price',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('purchase_price', $user->purchase_price),
			);

			$this->data['selling_price'] = array(
				'name'  => 'selling_price',
				'id'    => 'selling_price',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('selling_price',$user->selling_price),
			);
			
			$this->data['opening_stock'] = array(
				'name'  => 'opening_stock',
				'id'    => 'opening_stock',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('opening_stock', $user->opening_stock),
			);
			
			$this->data['branch_rack'] = array(
				'name'  => 'branch_rack',
				'id'    => 'branch_rack',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('branch_rack'),
			);
			

			$this->data['alert_quantity'] = array(
				'name'  => 'alert_quantity',
				'id'    => 'alert_quantity',
				'type'  => 'text',
				'value' => $this->form_validation->set_value('alert_quantity', $user->alert_quantity),
			);

			
		
		
		/*$this->data['phone2'] = array(
			'name'  => 'phone2',
			'id'    => 'phone2',
			'type'  => 'text',
			'class' => 'span2',
			'value' => $this->form_validation->set_value('phone2', $user->phone[1]),
		);
		$this->data['phone3'] = array(
			'name'  => 'phone3',
			'id'    => 'phone3',
			'type'  => 'text',
			'class' => 'span2',
			'value' => $this->form_validation->set_value('phone3', $user->phone[2]),
		);*/
		
		$this->data['submit'] = array(
			'name' => 'submit',
			'id'   => 'submit',
			'type' => 'submit',
			'value' =>'Save Edit',
			'class' =>'btn btn-success'
		);
		
		//print_r($this->data);exit;
		$this->data['page_title'] = "Edit product";
		 $this->load->view('common/header',$this->data);
		$this->load->view('product/product/edit_product', $this->data, $id);
		 $this->load->view('common/footer');
	}

	function delete_product($id){
		
		$this->product_model->delete($id);
		redirect("product/product/get_all_product");
	
	}
	
	function checkgroup($str){
		if($str==0){
			$this->form_validation->set_message('checkgroup', 'The %s field can not be Empty! ');
			return FALSE;
			}else{
				return TRUE;
				}
				
			}
		
	
	function check_product(){
		if($this->product_model->check_product($this->input->post('name'),$this->input->post('group'))){
					$this->form_validation->set_message('check_product', 'product Exists With The same group');
					return FALSE;
			}else{
				return TRUE;
		}
	
		}
	
	
	function check_category_name(){
	if($this->input->post('id_category')== 0 && $this->input->post('cat_name')==''){
		$this->form_validation->set_message('check_category_name', 'The %s field can not be Empty! ');
		return FALSE;
	}else{
		return TRUE;
	}
	}
	
	function check_company_name(){
	if($this->input->post('id_company')== 0 && $this->input->post('comp_name')==''){
		$this->form_validation->set_message('check_company_name', 'The %s field can not be Empty! ');
		return FALSE;
	}else{
		return TRUE;
	}
	}

	function check_unit_name(){
	if($this->input->post('id_unit')== 0 && $this->input->post('unit_name')==''){
		$this->form_validation->set_message('check_unit_name', 'The %s field can not be Empty! ');
		return FALSE;
	}else{
		return TRUE;
	}
	}



	function  check_category(){
		
		$data = $this->product_model->check_category(trim($_REQUEST['name']));
		echo $data;exit;
	}
	function  check_company(){
		
		$data = $this->product_model->check_company(trim($_REQUEST['name']));
		echo $data;exit;
		
	}
	function  check_unit(){
		
		$data = $this->product_model->check_unit(trim($_REQUEST['name']));
		echo $data;exit;
	}

	function find_product(){
		
		$data = $this->product_model->find_product($_REQUEST['id_branch'],$_REQUEST['id_product']);
		echo  $data['opening_stock']."-".$data['branch_rack'];
		
	}
	
	
	function update_branch(){
		
		$data = $this->product_model->update_branch($_REQUEST['id_branch'], $_REQUEST['id_product'],$_REQUEST['opening_stock'],$_REQUEST['branch_rack']);
	
	}
public function import()
{
$config['upload_path'] = './upload/product/';
		$config['allowed_types'] = 'xls|xls';
		$config['max_size']	= '20480';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';
		$this->load->library('upload',$config);
       $userfile = $_FILES['sel_file']['name'];
	  $tmpName  = $_FILES['sel_file']['tmp_name'];
	 
      $data =array( 'upload_data' => move_uploaded_file($tmpName,"./upload/product/$userfile"));	
	
		$filename=$userfile;
		
if (($handle = fopen(base_url()."upload/product/$filename", "r")) !== FALSE) {
	    	while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
    	    	$num = count($data);
      			// 	echo "<p> $num fields in line $row: <br /></p>\n";
       		 	//$row++;
        		$new_data = array();
				for ($c=0; $c < $num; $c++) {
       		 	  $new_data[] =$data[$c];
        		}
    		$final_data[] = $new_data;
			}
		
		    foreach($final_data as $key=>$fd){
 	    	if($key!=0){
			    $category_id=$this->product_model->get_category_product($fd[2]);
				$company_id=$this->product_model->get_company_product($fd[3]);
				$unit_id=$this->product_model->get_unit_product($fd[7]);
				$data['name'] = $fd[0];
				$code=$fd[1];
				$data['code'] = strtoupper($fd[1]);
				$data['id_category'] = $category_id;
				$data['id_company'] = $company_id;
				$data['purchase_price'] = strtoupper($fd[4]);
				$data['selling_price'] = strtoupper($fd[5]);
				$data['opening_stock'] = strtoupper($fd[6]);
				$data['id_unit'] = $unit_id;
				$data['alert_quantity']=$fd[8];
				$data['ip']= $_SERVER['REMOTE_ADDR'];
			
				$this->product_model->insert_product($data,$code);		
				}

}
}
redirect("product/product/get_all_product");
}

}
	

?>